from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from app01 import models


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request, *args, **kwargs):
        # 用户认证
        # 1. 读token
        # 2. 认证合法性
        # 3. 返回值
        #   3.1 认证成功：返回值【返回一个元组】 (11,22) 对应 [request.user, request.auth],
        #       元祖第一个对应是request.user，第二个对应是request.auth
        #   3.2 认证失败：抛出异常，返回错误信息
        #   3.3 返回None  多个认证类 【认证类1，认证类2，认证类3,....】,返回None会继续往后面走继续认证 最后匿名用户
        "/xxxx/xxx/?token=12344"
        # token = request._request.GET.get('token')
        token = request.query_params.get('token')
        if token:
            return ("summer", token)
        # raise AuthenticationFailed("认证失败")
        raise AuthenticationFailed({"code": 100000, "msg": "认证失败"})
    # def authenticate_header(self, request):
    #     return "api"


class QueryParamsAuthentication(BaseAuthentication):
    def authenticate(self, request, *args, **kwargs):
        # 用户认证
        # 1. 读token
        # 2. 认证合法性
        # 3. 返回值
        #   3.1 认证成功：返回值【返回一个元组】 (11,22) 对应 [request.user, request.auth],
        #       元祖第一个对应是request.user，第二个对应是request.auth
        #   3.2 认证失败：抛出异常，返回错误信息
        #   3.3 返回None  多个认证类 【认证类1，认证类2，认证类3,....】,返回None会继续往后面走继续认证 最后匿名用户
        "/xxxx/xxx/?token=12344"
        # token = request._request.GET.get('token')
        token = request.query_params.get('token', "")
        print(f'token={token}')
        obj_user = models.UserInfo.objects.filter(token=token).first()
        print(f'obj_user={obj_user}')
        if obj_user:
            return obj_user, obj_user.token  # request.user = 用户对象，request.auth=token
        # raise AuthenticationFailed("认证失败")
        # raise AuthenticationFailed({"code": 100000, "msg": "认证失败"})
        return

    def authenticate_header(self, request):
        return "api"


class HeaderAuthentication(BaseAuthentication):
    def authenticate(self, request, *args, **kwargs):
        token = request.META.get("HTTP_AUTHORIZATION", "")
        print(f'token={token}')
        obj_user = models.UserInfo.objects.filter(token=token).first()
        print(f'obj_user={obj_user}')
        if obj_user:
            return obj_user, obj_user.token  # request.user = 用户对象，request.auth=token
        return

    def authenticate_header(self, request):
        return "api"


class NoAuthentication(BaseAuthentication):
    def authenticate(self, request, *args, **kwargs):
        raise AuthenticationFailed({"status": False, "msg": "认证失败"})

    def authenticate_header(self, request):
        return "api"
